<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :shower="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template v-slot:after>
          <el-button type="success" @click="$router.push('/import')"
            >导入</el-button
          >
          <el-button type="danger" @click="excleDate">导出</el-button>
          <el-button type="primary" @click="showDialog = true"
          :disabled="!checkPermission('POINT-USER-ADD')"
            >新增员工</el-button
          >
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list" align="center">
          <el-table-column
            label="序号"
            align="center"
            type="index"
            sortable=""
          />
          <el-table-column
            label="姓名"
            sortable=""
            align="center"
            prop="username"
          />
          <el-table-column label="李路平头像" align="center">
            <template slot-scope="{ row }">
              <img
                @click="showQrCode(row.staffPhoto)"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                slot="reference"
                v-imageerror="require('@/assets/common/bigUserHeader.png')"
                alt=""
              />
            </template>
          </el-table-column>
          <!-- <el-table-column label="头像" align="center">
            <template slot-scope="{ row }">
              <img
                slot="reference"
                v-imageerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
              />
            </template>
          </el-table-column> -->
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            :formatter="formatEmployment"
            prop="formOfEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template slot-scope="scope">
              <el-switch :value="scope.row.enableState === 1"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)"
                >角色</el-button
              >
              <el-button type="text" size="small" @click="delEmployee(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :total="page.total"
            :current-page.sync="page.page"
            :page-size="page.size"
            layout="total, prev, pager, next"
          />
        </el-row>
      </el-card>
    </div>
    <add :show-dialog.sync="showDialog" />
    <el-dialog
      title="二维码"
      :visible.sync="showCodeDialog"
      @close="imgUrl = ''"
    >
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 引入分配员工权限 -->
    <assign-role
      :showRoleDialog.sync="showRoleDialog"
      ref="assignRole"
      :userId="userId"
    ></assign-role>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee, addEmployee } from '@/api/employees'
// 引入格式文档
import EmployeeEnum from '@/api/constant/employees'
import add from './components/add-employee'
// 引入事件处理格式
import { formatDate } from '@/filters'
// 引入员工处理格式
import { hireType } from '@/api/constant/employees'
// 引入二维码
import QrCode from 'qrcode'
// 引入员工权限分配
import assignRole from './components/assign-role.vue'
export default {
  components: { add, assignRole },
  data() {
    return {
      userId: null,
      showRoleDialog: false,
      // 二维码
      showCodeDialog: false,
      showDialog: false,
      loading: false,
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0
      }
    }
  },
  methods: {
    // 引入员工权限分派
    async editRole(id) {
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    },
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！

        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, '1111111111') // 将地址转化成二维码

          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('222222')
      }
    },
    // 导出员工
    excleDate() {
      // 要做什么?? 得到一个表头 第二测试导出
      const headers = {
        手机号: 'mobile',
        姓名: 'username',

        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => {
        // 接下来做什么 数据
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.page.total
        })
        // 接下来有了数据 就是转化
        const data = this.formatJson(headers, rows)
        // 定义一个复杂表头
        // const multiHeader = ["姓名", "主要信息", "", "", "", "部门"];

        // const merges = ["A1:A2", "B1:F1", "G1:G2"];
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers), //表头 必填
          data,
          filename: '天霸集团的员工表',
          multiHeader,
          merges
        })
      })
    },
    // 定义一个 讲数组转化为二位数组
    formatJson(headers, rows) {
      // 如何转化数组
      //  多组数据
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (
            headers[key] === 'timeOfEntry' ||
            headers[key] === 'correctionTime'
          ) {
            // return formatDate(item[headers[key]]);
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            // 怎么使用这个工具
            const obj = EmployeeEnum.hireType.find(
              obj => obj.id === item[headers[key]]
            )
            return obj ? obj.value : '不知道'
          }
          //一组数据
          return item[headers[key]] //单独的每一条数据
        })
      })
      // return rows.map(item =>
      //   Object.keys(headers).map(key => item[headers[key]])
      // );
    },
    // showDialog() {},
    // 枚举过滤数据
    formatEmployment(row, column, cellValue, index) {
      // console.log(12, row, 22, column, 33, cellValue, 44, index);
      //如何使用枚举 事件 1遍历 2 hireType的id === cellValue 3 返回 true false 4
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '位置'
    },
    // 获取table数据
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    handleSizeChange(val) {
      this.page.size = val
      this.getEmployeeList()
    },
    handleCurrentChange(val) {
      this.page.page = val
      this.getEmployeeList()
    },
    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm('今天晚上喝酒了,你确定要删除')
        await delEmployee(id)
        this.getEmployeeList()
        this.$message('恭喜你删除成功')
      } catch (error) {}
    }
  },
  created() {
    this.getEmployeeList()
  }
}
</script>

<style></style>
